<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\SystemAdmin;
use app\admincommon\controller\AdminController;

use app\BaseController;
use think\facade\Db;
use think\facade\View;

class Login extends AdminController{

    public function initialize(){
        parent::initialize();
        $action = $this->request->action();

        if (!empty(session('admin')) && !in_array($action, ['out'])) {
            $this->success('已登录，无需再次登录', [], __url('admin/Index/index'));
        }

    }



    public function index()
    {
        //$this->success("ok",[],"json",200000);

        $data = SystemAdmin :: select()->toArray();

        return View::fetch();

    }


    public function tologin(){

        if($this->request->isPost()){

            $post=$this->request->post();

            $admin = SystemAdmin::where(['username' => $post['username']])->find() ;

            if (empty($admin)) {
                $this->error('用户不存在');
            }
            
            if (password($post['password']) != $admin->password) {
                $this->error('密码输入有误');
            }
            
            if ($admin->status == 0) {
                $this->error('账号已被禁用');
            }
            
            $admin->login_num += 1;
            $admin->save();
            $admin = $admin->toArray();
            unset($admin['password']);
            
            $admin['expire_time'] = time() + 60*60*12;
            
            session('admin', $admin);
            $this->success('登录成功',[],__url('admin/Index/index'));

        }

        
    }
    
    
    
     /**
     * 用户退出
     * @return mixed
     */
    public function out()
    {
        session('admin', null);
        $this->success('退出登录成功', [], __url('admin/Login/index'));
    }


}
